

package com.yungu.swift.order.thread.driver.mileage;

import com.yungu.swift.assets.driver.model.dto.DriverStatusCycleDto;
import com.yungu.swift.assets.driver.service.DriverStatusCycleService;
import com.yungu.swift.base.SpringContextHolder;
import com.yungu.swift.lbs.model.DriverLocation;
import com.yungu.swift.lbs.service.LocationService;
import com.yungu.swift.order.dao.OrderMapper;
import com.yungu.swift.utils.DateUtils;
import com.yungu.swift.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;

/**
 * 用于异步插入司机里程统计的线程池
 *
 * @version 1.0
 * @date 2018/10/26 18:21
 */
public class StatisticsDriverMileageRunnable implements Runnable {
    private static final Logger logger = LoggerFactory.getLogger(StatisticsDriverMileageRunnable.class);
    private static final String IS_EXCEPTION = "isException";

    private DriverStatusCycleService driverStatusCycleService;
    private LocationService locationService;

    /**
     * 以下为需要插入到表中的字段
     */
    private String appid;
    private String driverUuid;
    private String orderUuid;
    private String carUuid;
    private int status;

    public StatisticsDriverMileageRunnable(DriverStatusCycleService driverStatusCycleService, LocationService locationService, String appid, String driverUuid, String orderUuid, String carUuid, int status) {
        this.driverStatusCycleService = driverStatusCycleService;
        this.locationService = locationService;
        this.appid = appid;
        this.driverUuid = driverUuid;
        this.orderUuid = orderUuid;
        this.carUuid = carUuid;
        this.status = status;
    }

    @Override
    public void run() {
        try {
            //出发去接乘客之后需要统计司机的空驶里程（空驶定义：订单结束后或者上班后到司机出发去接乘客之间的行驶里程）
            // 当前司机定位点
            String positionType = null;
            // 空驶
            if (DriverStatusCycleDto.EMPTY_RIDE == status) {
                positionType = "SJCF";
            }
            // 空载
            else if (DriverStatusCycleDto.EMPTY_CARRY == status) {
                positionType = "SJDD";
            }
            // 重载
            else if (DriverStatusCycleDto.SERVICE == status) {
                positionType = "CKXC";
            }
            List<Map<String, Object>> list = new ArrayList<>();
            double mileage = 0;
            Map<String, Object> objectMap = null;//locationService.getTodayLocationsByPositionType(driverUuid, positionType, orderUuid);
            if (null != objectMap) {
                //如果存在异常点的话 则里程和时长赋值为0
                if (!objectMap.containsKey(IS_EXCEPTION)) {
                    List<DriverLocation> driverLocationList = (List<DriverLocation>) objectMap.get("locationList");
                    int i = 0;
                    for (DriverLocation driverLocation : driverLocationList) {
                        Calendar c = Calendar.getInstance();
                        if (i < 1) {
                            c.setTime(driverLocation.getUploadTime());
                            c.set(Calendar.DATE, c.get(Calendar.DATE) - 2);
                            driverLocation.setUploadTime(c.getTime());
                        }
                        if (i < 3 && i >= 1) {
                            c.setTime(driverLocation.getUploadTime());
                            c.set(Calendar.DATE, c.get(Calendar.DATE) - 1);
                            driverLocation.setUploadTime(c.getTime());
                        }
                        i++;
                    }
                    Date today = new Date();//初始日期为今天
                    int day = 0;//初始天数
                    Map<String, Object> params = new HashMap<>();
                    for (DriverLocation driverLocation : driverLocationList) {
                        if (DriverStatusCycleDto.EMPTY_RIDE == status) {//空驶
                            if (!DateUtils.isSameDay(today, driverLocation.getUploadTime())) {//日期不等于初始日期
                                if (day > 0) {//出现跨天情况
                                    params.put("statusTimeSum", (driverLocation.getUploadTime().getTime() - today.getTime()));
                                    params.put("mileageSum", mileage);
                                    params.put("createdDate", today);
                                    list.add(params);
                                }
                                day++;//天数递增
                                mileage = 0;//里程清零
                                today = driverLocation.getUploadTime();//初始日期重新赋值为当前不等日期
                            }
                            if (DateUtils.isSameDay(today, driverLocation.getUploadTime())) {//日期等于初始日期
                                mileage += driverLocation.getDistance();//里程累计
                            }
                        } else {//不是空驶的情况
                            mileage += driverLocation.getDistance();//里程累计
                        }
                    }
                    params.clear();
                    long lastUploadTime = 0;
                    if (day == 0) {//未出现跨天情况
                        lastUploadTime = (long) objectMap.get("lastUploadTime");
                    } else {//出现跨天情况
                        lastUploadTime = today.getTime();
                    }
                    params.put("statusTimeSum", (System.currentTimeMillis() - lastUploadTime));
                    params.put("mileageSum", mileage);
                    params.put("createdDate", today);//当前初始日期
                    list.add(params);

                    for (Map<String, Object> stringObjectMap : list) {
                        double mileageSum = (double) stringObjectMap.get("mileageSum");
                        long statusTimeSum = (long) stringObjectMap.get("statusTimeSum");
                        Date createdDate = (Date) stringObjectMap.get("createdDate");
                        DriverStatusCycleDto driverStatusCycleDto = new DriverStatusCycleDto();
                        driverStatusCycleDto.setUuid(StringUtils.buildUUID());
                        driverStatusCycleDto.setAppid(appid);
                        driverStatusCycleDto.setCreateBy(driverUuid);
                        driverStatusCycleDto.setCreateOn(new Date());
                        driverStatusCycleDto.setRecordDate(createdDate);
                        driverStatusCycleDto.setDriverUuid(driverUuid);
                        driverStatusCycleDto.setCurrentOrderUuid(orderUuid);
                        // 前一个订单号
                        OrderMapper orderMapper = (OrderMapper) SpringContextHolder.getBean("orderMapper");
                        driverStatusCycleDto.setPrevOrderUuid(orderMapper.getTodayPrevOrderUuid(driverUuid));
                        // 车辆id 从司机表中取
                        driverStatusCycleDto.setCarUuid(carUuid);
                        driverStatusCycleDto.setMileage(mileageSum);
                        driverStatusCycleDto.setStatusTime((int) (statusTimeSum / 1000));
                        //里程状态
                        driverStatusCycleDto.setStatus(status);
                        params.clear();
                        params.put("driverUuid", driverUuid);
                        params.put("createdDate", DateUtils.format(createdDate, "yyyy-MM-dd"));
                        Integer maxSort = driverStatusCycleService.getTodayMaxSort(params).getData();
                        if (maxSort == null) {
                            maxSort = 0;
                        }
                        // 司机当天的统计里程排序
                        driverStatusCycleDto.setSort(maxSort + 1);
                        driverStatusCycleService.add(driverStatusCycleDto);
                    }
                }
            }
        } catch (Exception e) {
            logger.error("统计里程失败:", e);
            e.printStackTrace();
        }
    }
}
